const {Router} = require('express')
const router = new Router()

// 引入商品信息模型 goodsInformation
const GoodsInformationModel = require('../../../model/goodsInformation')
// 引入行政区域模型 areaList
const AreaListModel = require('../../../model/areaList')
// 引入用户模型user
const UserImformationModel = require('../../../model/userImformation')
// 引入解析MarkerDown的模块
const marked = require('../../../config/marked')
// 引入url
const url = require('../../../config/url')



const moveFile = require('../../../utils/fileUtils/moveFile')
const path = require('path')

function oprate(request, response, addressSearchResult){
    // const { goodsName, goodsSecondTitle, goodsThumb, isSell, searchFont, goodsDec, hostId, priceTable, goodsDecMD } = request.body
    const { goodsName, goodsSecondTitle, goodsThumb, isSell, addressCode, searchFont,  hostId, firstTitle, secondTitle, priceTable, pricePicArr, goodsDecMD, goodsDecPicArr } = request.body
    let goodsDec = marked ( goodsDecMD )

    const moveFileArr = [...goodsThumb, ...pricePicArr, ...goodsDecPicArr]

    // 因为移动文件我fs模块用的是异步方式，所以不得不用异步变同步的方式去得到最后移动的所有结果
    let statusArr = []
    Promise.all(moveFileArr.map( tmpPath =>{
        if (tmpPath){
            const fileName = (path.parse(tmpPath)).base
            const newFilePath = path.resolve(__dirname,'../../../public/free/goodsPic',fileName)
            const oldFilePath = path.resolve(__dirname,'../../../public/free/temp',fileName)

            return new Promise((resolve, reject) => {
                moveFile(newFilePath, oldFilePath, status => {
                    if (!status.isSuccess) statusArr.push(status);

                    resolve(true)
                })
            })
        }
    })).then( res =>{
        const data = {
            code: '200',
            data: 'error',
            msg: '上传失败！'
        }

        UserImformationModel.findOne({
            _id: hostId
        },function (err, doc) {
            if (err) return response.json(data);

            if (doc.roles.indexOf('admin') != -1 || doc.roles.indexOf('boss') != -1){
                let reg = new RegExp(url+'public/free/temp','g')
                // 因为g是全局匹配，所以会把匹配到的所有内容都替换
                goodsDec = goodsDec.replace( reg, url+'public/free/goodsPic' )
                const MD = goodsDecMD.replace( reg, url+'public/free/goodsPic' )
                // 正则遍历再返回变更后的数组
                let newGoodsThumb = goodsThumb.map(item=>{
                    return item.replace( reg, url+'public/free/goodsPic' )
                })
                // 正则遍历再返回变更后的数组
                let newPriceTable = priceTable.map(item=>{
                    item.pricePic = item.pricePic.replace( reg, url+'public/free/goodsPic' )
                    return item
                })

                let sellType = 0
                if (parseInt(isSell)==1) sellType = 0
                // 商品入库
                const Goods = new GoodsInformationModel({
                    goodsName,
                    goodsSecondTitle,
                    goodsThumb: newGoodsThumb,
                    isSell: sellType,
                    searchFont,
                    address: addressSearchResult,
                    addressCode,
                    firstTitle,
                    secondTitle,
                    priceTable: newPriceTable,
                    goodsDec,
                    goodsDecMD: MD,
                    hostId
                })

                if(statusArr.length == 0){
                    Goods.save(function (err) {
                        if (err) return response.json(data);

                        data.data = 'success'
                        data.msg = '上传商品成功'

                        response.json(data)
                    })
                }else {
                    statusArr.forEach(err=>{
                        console.log(err.err)
                    })
                    return response.json(data)
                }

            }else {
                data.msg = '用户权限不足'
                return response.json(data)
            }

        })
    })
}

router.post('/addGoods',function (request, response) {
    const { address } = request.body
    let addressSearchResult

    // 先进行地址结果的检索，前后端使用的address是一样的，后面再考虑后端传入数据给前端
    AreaListModel.aggregate()
        .unwind('areaList')
        .unwind('areaList.areaList')
        .match({
            'code': address[0],
            'areaList.code': address[1],
            'areaList.areaList.code': address[2]
        })
        .exec(function (err,doc) {
            if (err) return console.log(err);

            let data = doc[0]
            addressSearchResult = `${data.name} ${data.areaList.name} ${data.areaList.areaList.name}`

            oprate(request, response, addressSearchResult)
        })
})

module.exports = router
